import os
from gm.api import *
import numpy as np
from MSCI_tools import msci_tools as tools


def init(context):
    context.index = "SHSE.000010"
    context.threshod = 0.05
    subscribe(symbols=[context.index], frequency='60s')

    context.symbol_buy_price = {}

    context.num = 3


def on_bar(context, bars):
    now = context.now
    positions = context.account().positions()
    for position in positions:
        symbol = position['symbol']
        current_price = current(symbol)[0]['price']
        if (current_price > context.symbol_buy_price[symbol] * 1.3) or (
                current_price < context.symbol_buy_price[symbol] * 0.97):
            order_target_percent(symbol=symbol, percent=0, order_type=OrderType_Market, position_side=PositionSide_Long)
    last_day = get_previous_trading_date('SHSE', now)
    day_time, hour_and_mins = str(now).split(" ")

    symbol_list = []
    if hour_and_mins == '09:31:00':
        _symbol_list = tools.get_symbol_list(context.index, now)
        print(_symbol_list)

        for symbol in _symbol_list:
            data = history_n(symbol, frequency='1d', fields='close', count=14, end_time=last_day)
            close = tools.get_data_value(data, 'close')

            print(data, close)
            std = np.std(close)
            if std < context.threshod:
                symbol_list.append(symbol)
        print('-' * 10, now, ' ', symbol_list, '-' * 10)

    for symbol in symbol_list:
        volume = \
            history_n(symbol=symbol, frequency='60s', count=2, fields='volume', fill_missing='Last', end_time=now,
                      df=True)['volume'].values
        if volume[1] / volume[0] >= 5:
            current_price = \
                current(symbol=symbol, frequency='1d', count=1, fields='close', fill_missing='Last', end_time=now,
                        df=True)[
                    'close'].values
            if np.log(current_price / last_day) > 0:
                order_target_percent(symbol=symbol, percent=1. / (context.num), order_type=OrderType_Market,
                                     position_side=PositionSide_Long)
                context.symbol_buy_price[symbol] = current_price


if __name__ == '__main__':
    run(
        strategy_id='a5299b24-8b44-11e9-a4d4-b499baf0193a',
        filename='程序7_2策略.py',
        mode=MODE_BACKTEST,
        token='90be3f863b23ab3c1ef68d1f9b8dc06e4bebb30d',
        backtest_start_time='2018-01-01 09:00:00',
        backtest_end_time='2018-01-15 15:00:00',
        backtest_initial_cash=10000000,
        backtest_adjust=ADJUST_PREV,
    )
    print(os.path.basename(__file__))
